package com.linkoog.devtools.project_manager;

import com.linkoog.devtools.project_manager.settings.domain.ProjectInfo;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ProjectScanner {

    private static final List<String> IGNORE_DIR = Arrays.asList(".idea",".gradle","target", "out", "build", "idea-sandbox", "logs", "src", "node_modules", "doc");

    public static List<ProjectInfo> scan(String sourceDir, Consumer<String> consumer){
        Path source = Paths.get(sourceDir);
        return scan(source, consumer);
    }

    public static List<ProjectInfo> scan(Path source, Consumer<String> consumer){
        if (!Files.isDirectory(source)){
            return null;
        }

        ArrayList<ProjectInfo> list = new ArrayList<>();
        try {
            Files.walkFileTree(source, new SimpleFileVisitor<>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    final String dirName = dir.getFileName().toString();
                    if (isProject(dir)){
                        list.add(new ProjectInfo(dirName, dir.toAbsolutePath().toString()));
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    if (IGNORE_DIR.contains(dirName)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    consumer.accept("scan path " + dir.toAbsolutePath().toString());
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
        }

        return list;
    }

    private static boolean isProject(Path dir){
        Path workspacePath = dir.resolve(".idea/workspace.xml");
        return Files.isRegularFile(workspacePath);
    }





}
